package javaInterview;

public class OddEvenPrinter {
    private static final Object lock = new Object();
    private static volatile int number = 1; // 当前要打印的数字
    private static final int MAX = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(() -> {
            while (number <= MAX) {
                synchronized (lock) {
                    // 如果当前是偶数，奇数线程等待
                    if (number % 2 == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    } else {
                        // 打印奇数
                        System.out.println("奇数线程: " + number);
                        number++;
                        lock.notify(); // 唤醒另一个线程
                    }
                }
            }
        }, "OddThread");

        Thread evenThread = new Thread(() -> {
            while (number <= MAX) {
                synchronized (lock) {
                    // 如果当前是奇数，偶数线程等待
                    if (number % 2 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    } else {
                        // 打印偶数
                        System.out.println("偶数线程: " + number);
                        number++;
                        lock.notify(); // 唤醒另一个线程
                    }
                }
            }
        }, "EvenThread");

        oddThread.start();
        evenThread.start();
    }
}